<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/21
 * Time: 15:31
 */

namespace app\api\model;


class GoodsCategory extends BaseModel
{
    protected $visible = ['id','cates_name','goods','pic'];

    public function getPicAttr($value,$data)
    {
        $finalUrl = $value;
        if($data['pic_origin'] == 0){
            $finalUrl = config('setting.img_prefix').$value;
        }
        return $finalUrl;
    }



    public function goods()
    {
        return $this->hasMany('Goods','category','id');
    }


    //此处为admin/food控制器调用的方法获取组合后的分类数据(此处为递归查询,查询结果为树形数组)
    public static function getGoodsCategory($parent_id=0)
    {
        $res = self::where(['parent_id'=>$parent_id])->order(['id'=>'asc'])->select();
        foreach($res as $k=>$v){
            $res[$k]->data('child',self::getGoodsCategory($v->id));
            $res[$k]->data('goods',Goods::where(['category' => $v->id,'is_on_sale' => 1])->with('goodsImage')->select());
        }
        return $res;
    }




    //返回完整排序后的数据
    public static function getGoodsOrder()
    {
        return self::getTree(self::order(['level'=>'asc'])->select());
    }

    //获取二维数组排序的方法
    private static function getTree($data,$parent_id=0)
    {
        static $_ret = array();
        foreach($data as $k=>$v){
            if($v->parent_id == $parent_id){
                $_ret[] = $v;
                self::getTree($data,$v->id);
//                $_ret = array_merge($_ret,self::getTree($data,$v->id));
            }
        }
        return $_ret;
    }

}